package leetcode; /**
 * description:
 * author:zt
 * date:2021-10-04
 */

/**
 * 给定一个正整数 n ，输出外观数列的第 n 项。
 * 输入：n = 4
 * 输出："1211"
 * 解释：
 * countAndSay(1) = "1"
 * countAndSay(2) = 读 "1" = 一 个 1 = "11"
 * countAndSay(3) = 读 "11" = 二 个 1 = "21"
 * countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"
 */
public class leetcode38 {
    StringBuilder sb = new StringBuilder();
    public String countAndSay(int n) {
        return solve(String.valueOf(1),n,1);
    }
    public String solve(String s,int n,int depth){
        if (depth == n) return s;
        int count = 1;
        for (int i = 0; i < s.length(); i++) {
            char cur = s.charAt(i);
            while (i+1<s.length() && s.charAt(i+1)==cur) {
                count ++;
                i++;
            }
            sb.append(count);
            sb.append(cur);
            count = 1;
        }
        String next = sb.toString();
        sb.delete(0,sb.length());
        return solve(next,n,depth+1);
    }
}
